package io.nutz.nutzsite.module.exam.controller;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.source.ByteArrayOutputStream;

import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.*;
import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.excel.ExportExcel;
import io.nutz.nutzsite.module.exam.models.*;
import io.nutz.nutzsite.module.exam.services.PaperdefService;
import io.nutz.nutzsite.module.exam.services.QuestionService;
import io.nutz.nutzsite.module.exam.services.ScoresService;
import io.nutz.nutzsite.module.exam.services.VscoresService;
import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.services.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;



/**
 * 成绩与试卷 信息操作处理
 * 
 * @author lrw
 * @date 2020-04-08
 */
@IocBean
@At("/exam/scores")
public class ScoresController {
	private static final Log log = Logs.get();
public String paperPath="d:\\papers\\";
	@Inject
	private ScoresService scoresService;
	@Inject
	private VscoresService vscoresService;
	@Inject
	private PaperdefService paperdefService;
	@Inject
	private QuestionService questionService;
	@Inject
	private UserService userService;
	
	@RequiresPermissions("exam:scores:view")
	@At("")
	@Ok("th:/exam/scores/paperdef.html")
	public void index(HttpServletRequest req) {

	}

	//@RequiresPermissions("exam:scores:view")
	@At("/lookscore/?")
	@Ok("th:/exam/scores/scores.html")
	public void lookscore(String id, HttpServletRequest req) {
		Paperdef paperdef=paperdefService.fetch(id);		
		req.setAttribute("paperdef", paperdef);
	}
	/**
	 * 查询成绩与试卷列表
	 */
	@RequiresPermissions("exam:scores:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("uid") String uid,
					   @Param("ksid") String ksid,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(uid)){
			cnd.and("uid", "like", "%" + uid +"%");
		}
		cnd.and("ksid", "=", ksid);
		return scoresService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增成绩与试卷
	 */
	@At("/add")
	@Ok("th:/exam/scores/add.html")
	public void add( HttpServletRequest req) {

	}

	/**
	 * 新增保存成绩与试卷
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:scores:add")
	@Slog(tag="成绩与试卷", after="新增保存成绩与试卷 id=${args[0].id}")
	public Object addDo(@Param("..") Scores scores,HttpServletRequest req) {
		try {
			scoresService.insert(scores);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改成绩与试卷
	 */
	@At("/edit/?")
	@Ok("th:/exam/scores/edit.html")
	public void edit(String id, HttpServletRequest req) {
		Scores scores = scoresService.fetch(id);
		req.setAttribute("scores",scores);
	}

    /**
     * 详情成绩与试卷
     */
    @At("/detail/?")
    @Ok("th:/exam/scores/detail.html")
    public void detail(Integer id, HttpServletRequest req) {
		Scores scores = scoresService.fetch(id);
		String paperdata=scores.getPaperdata();
		req.setAttribute("now0", DateUtils.getDateTime());
		User user=userService.getField("^(id|userName|deptId|classg)$", scores.getUid());
		Paper paper=Json.fromJson(Paper.class,paperdata);
		
		NutMap qtidmap=paper.getQtidmap();
		NutMap qtidmap2=new NutMap();

		for(String key : qtidmap.keySet()){
			NutMap map=(NutMap)qtidmap.get(key);
			//NutMap idscoremap=(NutMap)map.get("idscore");
			//======================================================
			String qids=map.getString("qids");
			String[] qscores=map.getString("qscores").split(",");
			String[] stuans=map.getString("stuans").split(",");
			String[] stuscore=map.getString("stuscore").split(",");
			List<Question> qlist=questionService.query("^(id|qtid|name|ansA|ansB|ansC|ansD|qans)$",Cnd.where("id","in",qids).asc("instr(',"+qids+",',concat(',',id,','))"));
			int i=0;
			for(Question question:qlist){
				question.setQscore(Float.parseFloat( qscores[i]));
				question.setStuscore(Float.parseFloat( stuscore[i]));
				if(stuans[i].equals("-")) question.setStuans("");
				else question.setStuans(stuans[i]);
				i++;
			}
			NutMap map2=new NutMap();
			map2.addv("qlist", qlist);
			map2.addv("qname", map.getString("qname"));
			map2.addv("qscore", map.getString("qscore"));
			map2.addv("score", map.getAs("score", Float.class));
			qtidmap2.addv(key, map2);
		}
		qtidmap.clear();
		paper.setQtidmap(null);
		paper.setQtidmap(qtidmap2);
		
		req.setAttribute("paper", paper);
		req.setAttribute("user", user);
	}
	@At("/pdfpaper/?")
	@Ok("json")
	public Object createPdf(Integer id, HttpServletRequest req) {
		try {
			paper2pdf(id, paperPath );
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return Result.success("system.success");
	}
	@At("/pdfblankpaper/?")
	@Ok("json")
	public Object createPdf2(Integer id, HttpServletRequest req) {
		try {
			paper2blankpdf(id, paperPath );
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return Result.success("system.success");
	}

    /**
	 * 修改保存成绩与试卷
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:scores:edit")
	@Slog(tag="成绩与试卷", after="修改保存成绩与试卷")
	public Object editDo(@Param("..") Scores scores,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(scores)){

				scoresService.update(scores);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * paperdata首先合成html，然后再转换成pdf
	 * 是否因table太多，耗时过长，大约2卷/分钟
	 * 取消大量table，效率正常
	 * @param id
	 * @param dest
	 */
	public void paper2pdf(Integer id,String dest){
		//Date d1=new Date();
	Scores scores = scoresService.fetch(id);
	String paperdata=scores.getPaperdata();
	User user=userService.getField("^(id|userName|deptId|classg)$", scores.getUid());
	Paper paper=Json.fromJson(Paper.class,paperdata);

	NutMap qtidmap=paper.getQtidmap();
	NutMap qtidmap2=new NutMap();
	String html="";
	html+="<!DOCTYPE html>\n" +
			"<html xmlns='http://www.w3.org/1999/xhtml'>\n" +
			"<head>\n" +
			"    <meta charset='utf-8'>\n" +
			"    <title>FCRE2.0--试卷详情</title>\n" +
			"    <style>\n" +
			"body{width:700px;} table {max-width: 100%;background-color: transparent;border-collapse: collapse;border-spacing: 0;border-bottom: 1px solid #e7eaec!important;}h1 {font-size: 20px;}   " +
			"span.st1{font-size:14.0pt;font-family:SimSun;color:black;}span.tscore{font-size:12.0pt;font-family:SimSun;color:red;}span.tscore2{font-size:12.0pt;font-family:SimSun;color:blue;}span.ti{font-size:12.0pt;font-family:SimSun;color:blue;}span.tscore3{font-size:60.0pt;font-family:Helvetica;font-style: italic;color:red;}.paperheader{width:680px; border:2px; border-bottom: 2px double #080808!important;margin-bottom: 5px;}" +
			".paperscore td,.paperscore th{border: 2px solid #191818; border-bottom: 2px solid #000!important;}#div_processor1 {border: solid 1px #ddd;text-align: center;}#div_processor1 div {float: left;width: 100%;}#div_processor_fastto1 {max-height: 500px;}#div_processor_fastto1 dt {font-weight: bold;background: #eee;line-height: 25px;padding-left: 5px;font-size: 12px;clear: both;text-align: left;}#div_processor_fastto1 dd {line-height: 25px;padding: 5px 0;margin: 0;clear: both;}#div_processor1 a.finished {background: #3c0;color: #fff;}#div_processor1 a {color: #000;display: block;float: left;padding: 2px;border: solid 1px #ddd;background: #fff;width: 25px;margin-right: 2px;margin-bottom: 2px;text-decoration: none;line-height: 20px;}#div_processor1 a.wrong {background: #f00;color: #fff;}#div_processor1 a:hover {background: #fa0;}.tm_paper {min-width: 600px;}.tm_paper_section {margin: 10px 0;border: solid 1px #ddd;}.tm_paper_section h1 {background-color: rgba(255, 193, 7, 0.85);margin: 0;padding: 0 10px;line-height: 30px;cursor: pointer;}.tm_paper_question {margin: 5px 0;width: 100%;}.tm_paper_question thead tr th {width: 40px;text-align: right;padding-right: 5px;}.tm_paper_question td.tom_exam_score {width: 50px;text-align: right;color: #FF5722;padding-right: 10px;vertical-align: top;}" +
			".tm_paper_question tbody tr td {padding: 0 0 10px 0;}.tm_paper_section ul {list-style: none;margin: 0;padding: 0 0 0 40px;}.tm_paper_section ul li {list-style: none;margin: 0;padding: 0;line-height: 20px;}.tm_question_lineheight cite {background: #368ee0;padding: 0 5px;margin: 3px 5px;font-style: normal;color: #fff;min-width: 20px;display: block;text-align: center;line-height: 25px;}label {display: block;font-size: 14px;margin-bottom: 5px;}pre {display: block;padding: 9.5px;margin: 0 0 10px;font-size: 13px;line-height: 20px;word-break: break-all;word-wrap: break-word;white-space: pre;white-space: pre-wrap;background-color: #f5f5f5;border: 1px solid #ccc;border: 1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;color:#000;}" +
			"dl{display:block;}    </style>\n" +
			"</head>\n" +
			"<body ><div class='container-fluid'>\n" +
			"<div id='mydata' class='row-fluid'>\n" +
			"<div class='span8'>\n" +
			"<div class='container'>\n" +
			"<div class=''>";
	html+="<h1 style='text-align:center;font-size: 24px;'>"+paper.getName()+"</h1>";
	html+="<table class='paperheader' >\n" +
			"  <tr>\n" +
			"  <td width='480' height='41'>";
	html+="<span>考试时长："+paper.getDuration()+" 分钟&nbsp;&nbsp;</span>\n" +
			"<span>卷面总分："+paper.getTotalScore()+"</span>";
	html+="</td>\n" +
			"  <td width='200' rowspan='3'  align='left' valign='bottom'>" +
			"<span class='tscore3'>"+paper.getStuScore()+"</span></td>\n" +
			"  </tr>";
	html+="<tr>\n" +
			"  <td height='38'>" +
			"<b><span>班级： "+user.getClassg()+"&nbsp;&nbsp;" +
			"姓名："+user.getUserName()+"&nbsp;&nbsp; " +
			"考号："+user.getId()+"&nbsp;&nbsp;" +
			"成绩：</span></b></td>\n" +
			"  </tr>\n" +
			"</table>";
	String paperscore="<table class='paperscore' >\n" +
			"<tr >\n" +
			"<th width='80' scope='col'><span class='tscore2'>题目</span></th>";
	String paperscore2="</tr>\n" +
			"<tr style='text-align: center;'>\n" +
			"<td>得分</td>";
	String ticard="<div id='div_processor1'>\n" +
			"<div id='div_processor_fastto1'>";
	int idsseq=1;//试卷小题序列号1，2，3..
	String tm_main="<div class='tm_main'>\n" +
			"<div class='tm_container'>\n" +
			"<table border='0' width='100%' cellpadding='0' >\n" +
			"<tr>\n" +
			"<td valign='top'>\n" +
			"   <div class='tm_paper'>";
	for(String key : qtidmap.keySet()){
		NutMap map=(NutMap)qtidmap.get(key);
		//NutMap idscoremap=(NutMap)map.get("idscore");
		//======================================================
		String qname=map.getString("qname");//大题题型名称
		float score=map.getAs("score", Float.class);//大题得分
		String qscore=map.getString("qscore");//大题分值
		ticard+="<dl>\n" +
				"<dt>"+qname+"</dt>\n" +
				"<dd>" ;
		tm_main+="<div class='tm_paper_body'>\n" +
				"<div class='tm_paper_section'>\n" +
				"<h1  style='color:blue;'>"+ qname+"（"+qscore+"分）</h1>";
		String qids=map.getString("qids");
		String[] qscores=map.getString("qscores").split(",");
		String[] stuans=map.getString("stuans").split(",");
		String[] stuscore=map.getString("stuscore").split(",");
		List<Question> qlist=questionService.query("^(id|qtid|name|ansA|ansB|ansC|ansD|qans)$",Cnd.where("id","in",qids).asc("instr(',"+qids+",',concat(',',id,','))"));
		int i=0;
		String ticard2="";
		String tm_main2="";
		for(Question question:qlist){//每道小题
			float qscoresi=Float.parseFloat( qscores[i]);//小题分值
			float stuscorei=Float.parseFloat( stuscore[i]);//小题得分
			Integer questionId=question.getId();//小题原题号
			int qtid=question.getQtid();//小题题型编码
			//原题干中的双引号等信息、或者td中的内容太长，导致PDF不能创建
			String namei=question.getName().replace("/assets/","assets/").replace("\"content\"","").replace("\"","&quot;");//小题题干
			tm_main2+="<span class='span-quick-nav' id='quick-Q-"+questionId+"'></span>\n" +
					"  <table border='0' cellpadding='0' cellspacing='0' class='tm_paper_question' \n" +
					"   <thead>\n" +
					"   <tr style='background-color: #efebeb;'>\n" +
					"   <th valign='top' class='tm_question_lineheight'><cite>"+(idsseq)+"</cite></th>\n" +
					"    <td class='tm_question_lineheight' >"+namei+"</td>\n" +
					"    <td class='tom_exam_score'>";
			if(stuscorei==0) {
				ticard2 += "<a class='wrong' href='javascript:void(0);' onclick=''moveToQuestion('"+questionId+"')'' " +
						"id='fast_"+questionId+"' >"+(idsseq)+"</a>";
				tm_main2+="<img src='assets/img/error.png' />";
			}else{
				ticard2 += "<a class='finished' href='javascript:void(0);' onclick=''moveToQuestion('"+questionId+"')'' " +
						"id='fast_"+questionId+"' >"+(idsseq)+"</a>";
				tm_main2+="<img src='assets/img/success.png' />";
			}
			tm_main2+="</td>\n" +
					"</tr>\n" +
					" </thead>\n" +"</table>";
						/*" <tbody>\n" +
						" <tr>\n" +
						"<td colspan='3'>";*/
			if(stuans[i].equals("-")) question.setStuans("");
			else question.setStuans(stuans[i]);
			if(qtid==1 || qtid==2){//单选题、多选题
				tm_main2+="<ul>\n" +
						"<li><label style='margin-left: 2px;'>A.&nbsp;"+ question.getAnsA()+"</label></li>\n" +
						"<li><label style='margin-left: 2px;'>B.&nbsp;"+ question.getAnsB()+"</label></li>\n" +
						"<li><label style='margin-left: 2px;'>C.&nbsp;"+ question.getAnsC()+"</label></li>\n" +
						"<li><label style='margin-left: 2px;'>D.&nbsp;"+ question.getAnsD()+"</label></li>\n" +
						"<li><span class=tscore>参考答案："+question.getQans()+"</span></li>\n" +
						"<li><span class=tscore2>考生答案："+question.getStuans()+"</span></li>\n" +
						"</ul>";
			}else if(qtid==4){//判断题
				tm_main2+="<ul>\n" +
						"<li><label style='margin-left: 2px;'>A.&nbsp;"+ question.getAnsA()+"</label></li>\n" +
						"<li><label style='margin-left: 2px;'>B.&nbsp;"+ question.getAnsB()+"</label></li>\n" +
						"<li><span class=tscore>参考答案："+question.getQans()+"</span></li>\n" +
						"<li><span class=tscore2>考生答案："+question.getStuans()+"</span></li>\n" +
						"</ul>";
			}else if(qtid>=18 && qtid<=20){//acm编程1、2、3
				tm_main2+="<ul>\n" +
						"<li><span class=tscore2>"+question.getStuans()+"</span></li>\n" +
						"</ul>";
			}
				/*tm_main2+="</td>\n" +
						"   </tr>\n" +
						"    </tbody>\n" +
						"</table>";*/
			question.setQscore(qscoresi);
			question.setStuscore(stuscorei);
			if(stuans[i].equals("-")) question.setStuans("");
			else question.setStuans(stuans[i]);
			i++;
			idsseq++;
		}
		ticard+=ticard2+"</dd>\n" +
				"</dl>";
		tm_main+=tm_main2+" </div></div>";
		paperscore+="<th width='72' scope='col'><span class='tscore2' >"+qname+"</span></th>";
		paperscore2+="<td>"+score+"</td>";
	}
	paperscore+=paperscore2+"</tr>\n" +
			"</table><br>\n" +
			"</div>\n" +
			"</div>";
	ticard+="</div>\n" +
			"</div>";
	html+=paperscore+ticard+tm_main;

	html+="        </div>\n" +
			"\n" +
			"    </td>\n" +
			"</tr>\n" +
			"   </table>\n" +
			"</div>\n" +
			"</div>\n" +
			"</div>\n" +
			"\n" +
			"</div>\n" +
			"</div></body>\n" +
			"</html>";
		//Date d2=new Date();
	try {//src\main\resources\static\
		createPdf("http://127.0.0.1:8008/", html, dest + paper.getKsid() + "_" + user.getId() + ".pdf");
	}catch (Exception ex){
		ex.printStackTrace();
	}
		/*Date d3=new Date();
	log.info("生成html:"+DateUtils.getDistanceOfTwoDate(d1,d2,"s")+"\r\n生成pdf："
			+DateUtils.getDistanceOfTwoDate(d2,d3,"s"));*/
}
	public void paper2blankpdf(Integer id,String dest){
		//Date d1=new Date();
		Scores scores = scoresService.fetch(id);
		String paperdata=scores.getPaperdata();
		User user=userService.getField("^(id|userName|deptId|classg)$", scores.getUid());
		Paper paper=Json.fromJson(Paper.class,paperdata);

		NutMap qtidmap=paper.getQtidmap();
		NutMap qtidmap2=new NutMap();
		String html="";
		html+="<!DOCTYPE html>\n" +
				"<html xmlns='http://www.w3.org/1999/xhtml'>\n" +
				"<head>\n" +
				"    <meta charset='utf-8'>\n" +
				"    <title>FCRE2.0--试卷详情</title>\n" +
				"    <style>\n" +
				"body{width:700px;} table {max-width: 100%;background-color: transparent;border-collapse: collapse;border-spacing: 0;border-bottom: 1px solid #e7eaec!important;}h1 {font-size: 20px;}   " +
				"span.st1{font-size:14.0pt;font-family:SimSun;color:black;}span.tscore{font-size:12.0pt;font-family:SimSun;color:red;}span.tscore2{font-size:12.0pt;font-family:SimSun;color:blue;}span.ti{font-size:12.0pt;font-family:SimSun;color:blue;}span.tscore3{font-size:60.0pt;font-family:Helvetica;font-style: italic;color:red;}.paperheader{width:680px; border:2px; border-bottom: 2px double #080808!important;margin-bottom: 5px;}" +
				".paperscore td,.paperscore th{border: 2px solid #191818; border-bottom: 2px solid #000!important;}#div_processor1 {border: solid 1px #ddd;text-align: center;}#div_processor1 div {float: left;width: 100%;}#div_processor_fastto1 {max-height: 500px;}#div_processor_fastto1 dt {font-weight: bold;background: #eee;line-height: 25px;padding-left: 5px;font-size: 12px;clear: both;text-align: left;}#div_processor_fastto1 dd {line-height: 25px;padding: 5px 0;margin: 0;clear: both;}#div_processor1 a.finished {background: #3c0;color: #fff;}#div_processor1 a {color: #000;display: block;float: left;padding: 2px;border: solid 1px #ddd;background: #fff;width: 25px;margin-right: 2px;margin-bottom: 2px;text-decoration: none;line-height: 20px;}#div_processor1 a.wrong {background: #f00;color: #fff;}#div_processor1 a:hover {background: #fa0;}.tm_paper {min-width: 600px;}.tm_paper_section {margin: 10px 0;border: solid 1px #ddd;}.tm_paper_section h1 {background-color: rgba(255, 193, 7, 0.85);margin: 0;padding: 0 10px;line-height: 30px;cursor: pointer;}.tm_paper_question {margin: 5px 0;width: 100%;}.tm_paper_question thead tr th {width: 40px;text-align: right;padding-right: 5px;}.tm_paper_question td.tom_exam_score {width: 50px;text-align: right;color: #FF5722;padding-right: 10px;vertical-align: top;}" +
				".tm_paper_question tbody tr td {padding: 0 0 10px 0;}.tm_paper_section ul {list-style: none;margin: 0;padding: 0 0 0 40px;}.tm_paper_section ul li {list-style: none;margin: 0;padding: 0;line-height: 20px;}.tm_question_lineheight cite {background: #368ee0;padding: 0 5px;margin: 3px 5px;font-style: normal;color: #fff;min-width: 20px;display: block;text-align: center;line-height: 25px;}label {display: block;font-size: 14px;margin-bottom: 5px;}pre {display: block;padding: 9.5px;margin: 0 0 10px;font-size: 13px;line-height: 20px;word-break: break-all;word-wrap: break-word;white-space: pre;white-space: pre-wrap;background-color: #f5f5f5;border: 1px solid #ccc;border: 1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;color:#000;}" +
				"dl{display:block;}    </style>\n" +
				"</head>\n" +
				"<body ><div class='container-fluid'>\n" +
				"<div id='mydata' class='row-fluid'>\n" +
				"<div class='span8'>\n" +
				"<div class='container'>\n" +
				"<div class=''>";
		html+="<h1 style='text-align:center;font-size: 24px;'>"+paper.getName()+"</h1>";
		html+="<table class='paperheader' >\n" +
				"  <tr>\n" +
				"  <td width='480' height='41'>";
		html+="<span>考试时长："+paper.getDuration()+" 分钟&nbsp;&nbsp;</span>\n" +
				"<span>卷面总分："+paper.getTotalScore()+"</span>";
		html+="</td>\n" +
				"  <td width='200' rowspan='3'  align='left' valign='bottom'>" +
				"<span class='tscore3'></span></td>\n" +
				"  </tr>";
		html+="<tr>\n" +
				"  <td height='38'>" +
				"<b><span>班级： ____&nbsp;&nbsp;" +
				"姓名：____&nbsp;&nbsp; " +
				"考号：____&nbsp;&nbsp;" +
				"成绩：</span></b></td>\n" +
				"  </tr>\n" +
				"</table>";
		String paperscore="<table class='paperscore' >\n" +
				"<tr >\n" +
				"<th width='80' scope='col'><span class='tscore2'>题目</span></th>";
		String paperscore2="</tr>\n" +
				"<tr style='text-align: center;'>\n" +
				"<td>得分</td>";
		String ticard="<div id='div_processor1'>\n" +
				"<div id='div_processor_fastto1'>";
		int idsseq=1;//试卷小题序列号1，2，3..
		String tm_main="<div class='tm_main'>\n" +
				"<div class='tm_container'>\n" +
				"<table border='0' width='100%' cellpadding='0' >\n" +
				"<tr>\n" +
				"<td valign='top'>\n" +
				"   <div class='tm_paper'>";
		for(String key : qtidmap.keySet()){
			NutMap map=(NutMap)qtidmap.get(key);
			//NutMap idscoremap=(NutMap)map.get("idscore");
			//======================================================
			String qname=map.getString("qname");//大题题型名称
			float score=map.getAs("score", Float.class);//大题得分
			String qscore=map.getString("qscore");//大题分值
			ticard+="<dl>\n" +
					"<dt>"+qname+"</dt>\n" +
					"<dd>" ;
			tm_main+="<div class='tm_paper_body'>\n" +
					"<div class='tm_paper_section'>\n" +
					"<h1  style='color:blue;'>"+ qname+"（"+qscore+"分）</h1>";
			String qids=map.getString("qids");
			String[] qscores=map.getString("qscores").split(",");
			//String[] stuans=map.getString("stuans").split(",");
			//String[] stuscore=map.getString("stuscore").split(",");
			List<Question> qlist=questionService.query("^(id|qtid|name|ansA|ansB|ansC|ansD|qans)$",Cnd.where("id","in",qids).asc("instr(',"+qids+",',concat(',',id,','))"));
			int i=0;
			String ticard2="";
			String tm_main2="";
			for(Question question:qlist){//每道小题
				float qscoresi=Float.parseFloat( qscores[i]);//小题分值
				//float stuscorei=Float.parseFloat( stuscore[i]);//小题得分
				Integer questionId=question.getId();//小题原题号
				int qtid=question.getQtid();//小题题型编码
				//原题干中的双引号等信息、或者td中的内容太长，导致PDF不能创建
				String namei=question.getName().replace("/assets/","assets/").replace("\"content\"","").replace("\"","&quot;");//小题题干
				tm_main2+="<span class='span-quick-nav' id='quick-Q-"+questionId+"'></span>\n" +
						"  <table border='0' cellpadding='0' cellspacing='0' class='tm_paper_question' \n" +
						"   <thead>\n" +
						"   <tr style='background-color: #efebeb;'>\n" +
						"   <th valign='top' class='tm_question_lineheight'><cite>"+(idsseq)+"</cite></th>\n" +
						"    <td class='tm_question_lineheight' >"+namei+"</td>\n" +
						"    <td class='tom_exam_score'>";
				 {
					ticard2 += "<a class='' href='javascript:void(0);' onclick=''moveToQuestion('"+questionId+"')'' " +
							"id='fast_"+questionId+"' >"+(idsseq)+"</a>";
					//tm_main2+="<img src='assets/img/error.png' />";
				}
				tm_main2+="</td>\n" +
						"</tr>\n" +
						" </thead>\n" +"</table>";
						/*" <tbody>\n" +
						" <tr>\n" +
						"<td colspan='3'>";*/
				//if(stuans[i].equals("-")) question.setStuans("");
				//else question.setStuans(stuans[i]);
				if(qtid==1 || qtid==2){//单选题、多选题
					tm_main2+="<ul>\n" +
							"<li><label style='margin-left: 2px;'>A.&nbsp;"+ question.getAnsA()+"</label></li>\n" +
							"<li><label style='margin-left: 2px;'>B.&nbsp;"+ question.getAnsB()+"</label></li>\n" +
							"<li><label style='margin-left: 2px;'>C.&nbsp;"+ question.getAnsC()+"</label></li>\n" +
							"<li><label style='margin-left: 2px;'>D.&nbsp;"+ question.getAnsD()+"</label></li>\n" +
							//"<li><span class=tscore>参考答案："+question.getQans()+"</span></li>\n" +
							//"<li><span class=tscore2>考生答案："+question.getStuans()+"</span></li>\n" +
							"</ul>";
				}else if(qtid==4){//判断题
					tm_main2+="<ul>\n" +
							"<li><label style='margin-left: 2px;'>A.&nbsp;"+ question.getAnsA()+"</label></li>\n" +
							"<li><label style='margin-left: 2px;'>B.&nbsp;"+ question.getAnsB()+"</label></li>\n" +
							//"<li><span class=tscore>参考答案："+question.getQans()+"</span></li>\n" +
							//"<li><span class=tscore2>考生答案："+question.getStuans()+"</span></li>\n" +
							"</ul>";
				}else if(qtid>=18 && qtid<=20){//acm编程1、2、3
					tm_main2+="<ul>\n" +
							"<li><span class=tscore2>_________</span></li>\n" +
							"</ul>";
				}
				/*tm_main2+="</td>\n" +
						"   </tr>\n" +
						"    </tbody>\n" +
						"</table>";*/
				question.setQscore(qscoresi);
				/*question.setStuscore(stuscorei);
				if(stuans[i].equals("-")) question.setStuans("");
				else question.setStuans(stuans[i]);*/
				i++;
				idsseq++;
			}
			ticard+=ticard2+"</dd>\n" +
					"</dl>";
			tm_main+=tm_main2+" </div></div>";
			paperscore+="<th width='72' scope='col'><span class='tscore2' >"+qname+"</span></th>";
			paperscore2+="<td></td>";
		}
		paperscore+=paperscore2+"</tr>\n" +
				"</table><br>\n" +
				"</div>\n" +
				"</div>";
		ticard+="</div>\n" +
				"</div>";
		html+=paperscore+ticard+tm_main;

		html+="        </div>\n" +
				"\n" +
				"    </td>\n" +
				"</tr>\n" +
				"   </table>\n" +
				"</div>\n" +
				"</div>\n" +
				"</div>\n" +
				"\n" +
				"</div>\n" +
				"</div></body>\n" +
				"</html>";
		//Date d2=new Date();
		try {//src\main\resources\static\
			createPdf("http://10.6.19.253:8008/", html, dest + paper.getName() + "_样卷" + id + ".pdf");
		}catch (Exception ex){
			ex.printStackTrace();
		}
		/*Date d3=new Date();
	log.info("生成html:"+DateUtils.getDistanceOfTwoDate(d1,d2,"s")+"\r\n生成pdf："
			+DateUtils.getDistanceOfTwoDate(d2,d3,"s"));*/
	}

	public void createPdf(String html, String dest) throws IOException {
		HtmlConverter.convertToPdf(html, new FileOutputStream(dest));
	}
	ConverterProperties converterProperties;
	/**
	 *
	 * @param baseUri-img等资源的父目录
	 * @param html-网页内容字符串
	 * @param dest-pdf存储全文件夹名
	 * @throws IOException
	 */

	public void createPdf(String baseUri, String html, String dest) throws IOException {
		converterProperties = new ConverterProperties();
		DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
		defaultFontProvider.addFont("d:\\papers\\msyh.ttc,0");
		/*FontProvider fontProvider = new FontProvider();

		PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED);
		fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");*/
/*String fontPath="d:\\papers\\msyh.ttc,0";
		//添加自定义字体，例如微软雅黑
		if (StringUtils.isNotEmpty(fontPath)){
			PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H);
			fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);
		}*/

		converterProperties.setFontProvider(defaultFontProvider);

		converterProperties.setBaseUri(baseUri);
		HtmlConverter.convertToPdf(html, new FileOutputStream(dest), converterProperties);
	}
	/*public void createPdf(String baseUri, String src, String dest) throws IOException {
		HtmlConverter.convertToPdf(new File(src), new File(dest));
	}
	public void createPdf(string baseUri, string src, string dest)
{
	ConverterProperties properties = new ConverterProperties();
	properties.SetBaseUri(baseUri);
	HtmlConverter.ConvertToPdf(new FileStream(src, FileMode.Open), new FileStream(dest, FileMode.Create));
}*/
	/**
	 * 循环增加水印
	 * @param html 源文件
	 * @param text 水印文字
	 * @return 加过水印的文件字节数组
	 * @throws Exception 异常
	 */
	public byte[] addWaterMark(String html, String text) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		HtmlConverter.convertToPdf(html, outputStream, converterProperties);
		byte[] result = outputStream.toByteArray();
		outputStream.close();

		Font watermarkFont = FontFactory.getFont("d:\\papers\\msyh.ttc,0",
						BaseFont.IDENTITY_H, BaseFont.SUPERSCRIPT_SIZE,
						Font.BOLD, new GrayColor(0.2f));
		PdfReader reader = new PdfReader(result);
		PdfStamper stamp = new PdfStamper(reader, outputStream);
		PdfContentByte under;
		int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
		for (int i = 1; i <= pageSize; i++) {
			under = stamp.getUnderContent(i);// 水印在之前文本下
			for (int m = 0; m < 5; m++) {
				for (int n = 0; n < 5; n++) {
					ColumnText.showTextAligned(under, Element.ALIGN_CENTER, new Phrase(text,watermarkFont),
							(50.5f + m * 150), (40.0f + n * 150),45);
				}
			}
		}
		stamp.close();// 关闭
		reader.close();
		byte[] bytes = outputStream.toByteArray();
		// TODO
//        Path path = Paths.get("D:\\1111.pdf");
//        Files.write(path, bytes);
		outputStream.close();
		return bytes;
	}
	/**
	 * 删除成绩与试卷
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("exam:scores:remove")
	@Slog(tag ="成绩与试卷", after= "删除成绩与试卷:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			scoresService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
    @At
	@Ok("json")
    public Object export(@Param("ksid") String ksid,
			   HttpServletRequest req, HttpServletResponse response) {
    	Cnd cnd = Cnd.NEW();
		if(ksid!=null){
			cnd.and("ksid","=", ksid);
		}
    	List<Vscores> list = vscoresService.query(cnd);
    	
    	Paperdef paperdef=paperdefService.fetch(ksid);
    	String tname=paperdef.getName()+"_成绩数据";
		String fileName = tname + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel(tname, Vscores.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
    }
	@At("/exportpaper/?")
	@Ok("json")
	public Object export2(String ksid,HttpServletRequest req, HttpServletResponse response) {
		Cnd cnd = Cnd.NEW();
		if(ksid!=null){
			cnd.and("ksid","=", ksid);
		}else {
			return Result.error("ksid不能为空");
		}
		List<Scores> list = scoresService.query(cnd);

		Paperdef paperdef=paperdefService.fetch(ksid);

		String dest=paperPath+paperdef.getName()+"\\";
		Files.createDirIfNoExists(dest);
		try{
			for(Scores scores:list) {

				paper2pdf(scores.getId(),dest);
			}
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("生成pdf版试卷失败"+ex.getMessage());
		}
		return Result.success("已生成pdf版试卷"+ksid);
	}
}
